package com.my12306.user.controller.auth;

import com.my12306.common.enums.CodeEnum;
import com.my12306.common.util.PageUtils;
import com.my12306.common.util.response.ResponseData;
import com.my12306.user.model.po.auth.RoleEntity;
import com.my12306.user.model.vo.RoleVo;
import com.my12306.user.service.auth.RolePermissionService;
import com.my12306.user.service.auth.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.my12306.common.util.CommentUtils.getPoToVo;

/**
 * @Author:苏牧夕
 * @Date:2020-05-15 17:36:13
 * @Version 1.0
 */
@RestController
@RequestMapping("auth/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 列表
     */
    @GetMapping("/list")
    public ResponseData list(@RequestParam Map<String, Object> params) {
        PageUtils page = roleService.queryPage(params);

        return ResponseData.ok().put("page", page);
    }

    /**
     * 列表
     */
    @GetMapping("/select")
    public ResponseData selectlist(@RequestParam Map<String, Object> params) {
        List<RoleEntity> entities = roleService.selectAllRole();

        return ResponseData.ok().put("list", entities);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{roleId}")
    public ResponseData info(@PathVariable("roleId") Long roleId) {
        RoleEntity oauthRole = roleService.getById(roleId);
        RoleVo roleVo = new RoleVo();
        getPoToVo(oauthRole, roleVo);
        List<Long> ids = rolePermissionService.queryPermIdListByRoleId(roleId);
        roleVo.setMenuIdList(ids);
        return ResponseData.ok().put("role", roleVo);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public ResponseData save(@RequestBody RoleVo roleVo) {
        System.out.println("===============>roleVo=" + roleVo);
        if (roleService.saveRoleAndPerms(roleVo)) {
            return ResponseData.ok();
        } else {
            return ResponseData.fail(CodeEnum.ADD_FAIL.getCode(), CodeEnum.ADD_FAIL.getMessage());
        }
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public ResponseData update(@RequestBody RoleVo roleVo) {
        roleService.updateBatchRoleAndPerms(roleVo);

        return ResponseData.ok();
    }

    /**
     * 删除角色
     * 1.删除角色表
     * 2.删除用户-角色
     * 3.删除角色-资源
     */
    @DeleteMapping("/delete")
    public ResponseData delete(@RequestBody Long[] roleIds) {
        return roleService.deleteBatchByIds(Arrays.asList(roleIds));
    }

}
